#include <QApplication>
#include "wangge.h"
#include <QDebug>

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MYPORT    100000		/* 监听端口 */
#define BACKLOG 10
#define MAXDATASIZE 1000
void *server(void *arg1)
{

    wangge *w = (wangge *)arg1;
    char buf[MAXDATASIZE];
    char a[1000];
    int b, numbytes;
    char buf1[8]="goodbye";
    char *arg;


    int sockfd, new_fd; 		/* 监听端;口，数据端口 */
    struct sockaddr_in my_addr; 	/* 自身的地址信息 */
    struct sockaddr_in their_addr; 	/* 连接对方的地址信息 */
    socklen_t sin_size;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT); 		/* 网络字节顺序 */
    my_addr.sin_addr.s_addr = INADDR_ANY; 	/* 自动填本机IP */
    bzero(&(my_addr.sin_zero), 8); 		/* 其余部分置0 */

    if(bind(sockfd, (struct sockaddr *)&my_addr,
            sizeof(struct sockaddr)) == -1)
    {
        perror("bind");
        qDebug()<<"Bind";

        exit(1);
    }

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        qDebug()<<"Listen";
        exit(1);
    }

    while(1)
    /* 主循环 */
    {





    sin_size = sizeof(struct sockaddr_in);
    qDebug()<<"wait  for accept";
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
    if  (new_fd == -1) {
        perror("accept");
        qDebug()<<"Accept err";
    }


    printf("Got connection from %s\n",inet_ntoa(their_addr.sin_addr));

    qDebug()<<"Accepted";

        while(1)
        {

            if((numbytes=recv(new_fd,buf,MAXDATASIZE,0))==-1)
            {
                perror("recv");
                exit(1);
            }
            //buf[numbytes]='\0';
            printf("%s\n",buf);
            w->set_cpu(buf);
            //           sleep(2);
        }

    }
    close(new_fd); 		/* 无法生成子进程时有用 */




}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    wangge w;

    pthread_t p_id;

    pthread_create(&p_id,NULL,server,(void *)&w);


    w.show();

    return a.exec();
}
